package com.qf.mybatis925.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qf.mybatis925.utils.R;
import com.qf.mybatis925.entity.LoginUser;
import com.qf.mybatis925.entity.PageVO;
import com.qf.mybatis925.entity.User;
import com.qf.mybatis925.entity.UserDTO;
import com.qf.mybatis925.service.UserService;
import com.qf.mybatis925.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * --- 天道酬勤 ---
 *
 * @author QiuShiju
 * @date 2025/9/29
 * @desc
 */
@RestController
@RequestMapping("/api/user")
@Slf4j
@CrossOrigin(origins = {"http://localhost:8080"}) //  后端解决跨域问题,其后后期会配置前端的跨域问题
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private JwtUtils jwtUtils;

    /**
     * 登录
     * 使用User对象接收没问题,但是
     * 该对象中只有username和password,其他字段都为空
     * 一般封装一个LoginUser对象,只包含username和password字段
     */
    @PostMapping("/login")
    public R login(@RequestBody LoginUser loginUser) {
        String token = userService.login(loginUser);;
        System.out.println(token);
        return R.ok(token);
    }

    /**
     * 查询全部用户信息v1 无参
     * 查询全部用户信息v2 模糊
     * 查询全部用户信息v3 分页+搜索查
     * ps: get请求封装对象,不需要@RequestBody注解
     */
    @GetMapping("/list")
    public R list(UserDTO userDTO) {
        PageHelper.startPage(userDTO.getPageNum(), userDTO.getPageSize());

        List<User> list = userService.list(userDTO);
        if (list == null || list.size() == 0) {
            return R.fail("暂无数据");
        }

        PageInfo<User> pageInfo = new PageInfo<>(list);

        PageVO pageVO = new PageVO();
        pageVO.setPageNum(pageInfo.getPageNum());
        pageVO.setPageSize(pageInfo.getPageSize());
        pageVO.setTotal(pageInfo.getTotal());
        pageVO.setPages(pageInfo.getPages());
        pageVO.setList(pageInfo.getList());
        return R.ok(pageVO);
    }

    /**
     * 批量删除
     */
    @GetMapping("/del/batch")
    public R batchDelete(@RequestParam List<Integer> ids) {
        log.debug("批量删除用户ids:{}", ids);
        int count = userService.batchDelete(ids);
        if (count == 0) {
            return R.fail("删除失败");
        }
        return R.ok(count);
    }

    /**
     * 添加用户
     */
    @PostMapping("/add")
    public String add(@RequestBody User user) {
        userService.add(user);
        return "add";
    }
    /**
     * 修改用户
     */
    @PostMapping("/update")
    public R update(@RequestBody User user) {
        log.debug("修改用户:{}", user);
        int count = userService.update(user);
        if (count == 0) {
            return R.fail("修改失败");
        }return R.ok(count);
    }

    /**
     * 退出登录接口
     */
    @GetMapping("/logout")
    public R logout(HttpSession session){
        session.invalidate();
        return R.ok();
    }



}
